#!/usr/bin/python2
# Filename : autossh.py

import sys
import pexpect

DBG = 0

def dbg(msg):
    if DBG:
        print 'DBG: '+msg
    return msg

def ssh_cmd(remote, passwd, cmd):
    ssh = pexpect.spawn(dbg('ssh '+remote+' '+cmd))
    r = ''

    while 1 :
        i = ssh.expect(['Password: ', 'password: ', 'continue connecting (yes/no)?', pexpect.EOF, pexpect.TIMEOUT])
        r += ssh.before

        dbg(ssh.before)

        if ( i == 0 ) or ( i == 1 ) :
            dbg('Passwd: '+passwd)
            ssh.sendline(passwd)
            break
        elif i == 2 :
            dbg('continue connecting (yes/no)?yes')
            ssh.sendline('yes')
        elif i == 3 :
            dbg('pexpect.EOF')
            break
        elif i == 4 :
            dbg('pexpect.TIMEOUT')
            r += 'autossh.py: pexpect.TIMEOUT\n'
            ssh.close()
            return r

    dbg('loop end')

    i = ssh.expect(['Password: ', 'password: ', pexpect.EOF, pexpect.TIMEOUT])
    r += ssh.before
    ssh.close()

    if ( i == 0 ) or ( i == 1 ) :
        r += 'autossh.py: password error'
    elif ( i == 3 ) :
        r += 'autossh.py: pexpect.TIMEOUT'
    elif ( i != 2) :
        r += 'autossh.py: unknown error'

    return r

argc = len(sys.argv)

if argc == 4 :
    print ssh_cmd(sys.argv[1], sys.argv[2], sys.argv[3])
elif argc == 3 :
    print ssh_cmd(sys.argv[1], '', sys.argv[2])
else:
    print 'Usage:'
    print '\tautossh.py <remote> [passwd] <command>'

